/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-04-28 13:48:21
 * @LastEditTime: 2023-01-29 10:49:07
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, message, Table } from 'antd';
import { observer } from 'mobx-react-lite';
import { CheckCircleFilled } from '@ant-design/icons';
import { viewTestReport } from '@/api/standardizedDetection/detectionTask';
import { formatDate, isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';

import { useBusinessGuidanceContext } from '../contexts/BusinessGuidanceContext';
import { useGuidanceTypeContext } from '../contexts/GuidanceWaysContext';
import UpLoadBusiness from './dialogs/UpLoadBusiness';
import { sendGuidanceById } from '@/api/onlineAndVirtual/guidanceAndFeedback';
import SawInspection from './dialogs/SawInspection';
import { auditAnnualById } from '@/api/onlineAndVirtual/annualInspection';
import Guidance from './dialogs/Guidance';

const { Column } = Table;

const PageList = (props: any) => {
  const { className, guidanceUnitId } = props;
  const { type } = useGuidanceTypeContext();
  const {
    selectItems,
    getBusinessList,
    resultFilter,
    readFilter,
    setSelectKey,
    selectUnit,
    businessList,
    getEnclosure,
    enclosure,
    enclosureList
  } = useBusinessGuidanceContext();
  console.log('businessList', enclosure);

  const formatMessage = useFormatMessage();
  const [value, setValue] = useState(true);
  const [guidanceVisible, setGuidanceVisible] = useState(false);
  const [sawGuidanceVisible, setSawGuidanceVisible] = useState(false);
  const [sawInspectionVisible, setSawInspectionVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  // 表格数据
  const [reportList, setReportList] = useState({});

  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  /* 初始参数 */
  useEffect(() => {
    if (selectUnit) {
      const param =
        type === 3
          ? { guidanceUnitId, instructedUnitId: selectUnit.id }
          : { type, instructedUnitId: selectUnit.id, guidanceUnitId };
      setListQuery({
        pageNo: 1,
        pageSize: 10,
        param
      });
    }
  }, [selectUnit, guidanceUnitId]);
  /* 分页查询 */
  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);

      getBusinessList(listQuery, type)
        .then((res: any) => {
          setTotal(res?.totalCount);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /* 发送意见 */
  const clickReport = (item: any) => {
    sendGuidanceById(item).then(getBusinessList(listQuery, type).then(message.info('发送成功')));
    // .then((res) => {
    //   const { data } = res;
    //   setReportList(data);
    // });
  };
  /* true去查看年检，false去修改自身内容 */
  const ToGuidance = (value: any, disabled: boolean) => {
    // type===3?
    disabled
      ? auditAnnualById(value.id).then(
          getEnclosure(value.id, type).then(setSawInspectionVisible(true))
        )
      : getEnclosure(value.id, type).then(setGuidanceVisible(true));
  };
  /* 查看业务指导的指导内容 */
  const ToSawGuidance = (value: any) => {
    getEnclosure(value.id, type).then(setSawGuidanceVisible(true));
  };
  return (
    <div className={className}>
      <Table
        dataSource={businessList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        scroll={{ x: 'max-content' }}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />

        <Column
          title={type === 1 ? '受指导单位' : type === 2 ? '接收单位' : '来源单位'}
          dataIndex="instructedUnitName"
          key="instructedUnitName"
          align="center"
        />

        <Column
          title={type === 1 ? '指导单名称' : type === 2 ? '书面反馈名称' : '年检名称'}
          dataIndex="name"
          key="name"
          align="center"
        />
        {type === 3 && <Column title="年度" dataIndex="year" key="year" align="center" />}
        {type === 3 && (
          <Column title="接收时间" dataIndex="sendTime" key="sendTime" align="center" />
        )}
        {type === 3 && (
          <Column
            title="发送单位"
            dataIndex="instructedUnitName"
            key="instructedUnitName"
            align="center"
          />
        )}
        {type === 3 && (
          <Column title="发送人" dataIndex="operatorName" key="operatorName" align="center" />
        )}
        {type === 3 && (
          <Column title="说明" dataIndex="description" key="description" align="center" />
        )}
        {type !== 3 && (
          <>
            <Column
              title="创建时间"
              dataIndex="createTime"
              key="createTime"
              align="center"
              render={(text) => <span>{formatDate(text)}</span>}
            />
            <Column title="创建人" dataIndex="operatorName" key="operatorName" align="center" />
            <Column
              title="发送时间"
              dataIndex="sendTime"
              key="sendTime"
              align="center"
              width={120}
              render={(text) => <span>{formatDate(text)}</span>}
            />
          </>
        )}

        <Column
          title="状态"
          dataIndex="sendStatus"
          key="sendStatus"
          align="center"
          render={(status: number, record: any) => (
            <>{type === 3 ? readFilter(status) : resultFilter(status)}</>
          )}
        />
        {type === 3 ? (
          <Column
            title="查看年审资料"
            key="guidance"
            align="center"
            width={120}
            render={(_text, record: any) => (
              <>
                <Button type="link" onClick={() => ToGuidance(record, true)}>
                  查看
                </Button>
              </>
            )}
          />
        ) : (
          <Column
            title="指导意见"
            key="guidance"
            align="center"
            width={120}
            render={(_text, record: any) => (
              <>
                {record.sendStatus === 1 ? (
                  <Button type="link" onClick={() => ToGuidance(record, false)}>
                    编辑
                  </Button>
                ) : (
                  <Button type="link" onClick={() => ToSawGuidance(record)}>
                    指导意见
                  </Button>
                )}
              </>
            )}
          />
        )}
        <Column
          title="操作"
          key="action"
          align="center"
          render={(_text, record: any) => (
            <>
              {type === 3 ? (
                <Button
                  type="link"
                  onClick={() => ToGuidance(record, false)}
                  disabled={record.sendStatus === 1}
                >
                  审核
                </Button>
              ) : (
                <>
                  <Button
                    type="link"
                    onClick={() => clickReport(record.id)}
                    disabled={!(record.sendStatus === 1)}
                  >
                    发送
                  </Button>
                  {record.sendStatus !== 1 ? <CheckCircleFilled /> : <></>}
                </>
              )}
            </>
          )}
        />
      </Table>
      {useMemo(
        () =>
          enclosure && (
            <UpLoadBusiness
              visible={guidanceVisible}
              // disabled={value}
              onClose={() => {
                setGuidanceVisible(false);
              }}
              data={enclosure}
              enclosureList={enclosureList}
            />
          ),
        [guidanceVisible, enclosure]
      )}
      {useMemo(
        () =>
          enclosure && (
            <SawInspection
              visible={sawInspectionVisible}
              // disabled={value}
              onClose={() => {
                setSawInspectionVisible(false);
              }}
              data={enclosure}
              enclosureList={enclosureList}
            />
          ),
        [sawInspectionVisible, enclosure]
      )}
      {useMemo(
        () =>
          enclosure && (
            <Guidance
              visible={sawGuidanceVisible}
              // disabled={value}
              onClose={() => {
                setSawGuidanceVisible(false);
              }}
              data={enclosure}
              enclosureList={enclosureList}
            />
          ),
        [sawGuidanceVisible, enclosure]
      )}
    </div>
  );
};

export default observer(PageList);
